home *** CD-ROM | disk | FTP | other *** search
/ PC Plus SuperCD (UK) 1998 August / PC Plus SuperCD 50b Issue 142 (CD142b) (August 1998).iso / essent / FIXES / CSeries.exe / issue101 / CPROG18.CPP next >
Encoding:
C/C++ Source or Header  |  1995-02-28  |  1.9 KB  |  53 lines

  1. // CPROG18.CPP
  2. // A very simple object - Ctrl+F9 to compile and run, Alt+F5 to see output
  3.  
  4.  
  5. #include <iostream.h>    // Needed for cout and <<
  6.  
  7. class testobj {
  8.     int x, y;        // x and Y are private to testobj. Only member
  9.                 // functions are able to access them
  10. public:
  11.     testobj(void);        // Constructor - automatically executed when a
  12.                 // testobj object is created.
  13.     ~testobj(void);        // Destructor - executed when object destroyed
  14.     void printvals(void);    // A member function of testobj - the only way
  15.                 // for the outside world to access x and y.
  16.     };
  17.  
  18. testobj::testobj(void)        // Defintion of constructor function
  19. {
  20.     x=10;                   //...it simply initialises x and y
  21.     y=20;                   // and prints a message
  22.     cout << "A testobj-type object has been created\n";
  23. }
  24.  
  25. testobj::~testobj()        // Definition of destructor function
  26. {                  //...it just prints a message
  27.     cout << "A testobj-type object is being destroyed!\n";
  28. }
  29.  
  30. void testobj::printvals(void)    // Definition of printvals()
  31. {
  32.     cout << "x=" << x << '\n';    //...prints values of x and y
  33.     cout << "y=" << y << '\n';
  34. }
  35.  
  36. //So far we have only said what a testobj-type object looks like. None actual
  37. //objects have been created.
  38. /////////////////////////////////////////////////////////////////////////////
  39. void main(void)            // Program execution starts here
  40. {
  41. testobj fred;            // An instance of testobj is created, called
  42.                 // fred. At this point the constructor will
  43.                 // be executed.
  44.  
  45.     fred.printvals();    // Use printvals() member function to see
  46.                 // values of x and y.
  47. }                // End of program. Fred is destroyed as the
  48.                 // program cleans up before returning to DOS,
  49.                 // so the destructor is executed, causing the
  50.                 // farewell message to be printed.
  51. /////////////////////////////////////////////////////////////////////////////
  52. // Something to try - make fred an array of five objects... testobj fred[5];
  53. // and access one of those objects, eg fred[2].printvals();